<template>
  <div class="assets-page-container">
    <!-- 顶部导航栏（含右侧操作图标） -->
    <van-nav-bar
      title="资产管家"
      right-text="..."
      right-icon="eye-o"
      @click-right="handleNavRightClick"
    />

    <!-- 总资产卡片（按照图片布局调整） -->
    <div class="total-assets-card">
      <div class="card-title">净资产</div>
      <div class="card-amount">{{ netAssets.toFixed(2) }}</div>
      <div class="card-details">
        <div class="detail-item">
          <span class="detail-label">资产</span>
          <span class="detail-value">{{ assets.toFixed(2) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">负债</span>
          <span class="detail-value negative">{{ liabilities.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <!-- 资产列表区域 -->
    <div v-if="assetList.length > 0" class="asset-list-section">
      <div class="section-title">资产账户</div>
      <van-cell-group inset>
        <van-swipe-cell 
          v-for="item in positiveAssets" 
          :key="item.id"
        >
          <van-cell 
            :title="item.name" 
            :value="`¥${item.money.toFixed(2)}`"
            :label="item.remark"
            :icon="getAssetIcon(item.type)"
            @click="editAsset(item)"
            is-link
          />
          <template #right>
            <van-button 
              square 
              text="删除" 
              type="danger" 
              class="swipe-delete-button"
              @click="showDeleteConfirm(item)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>

      <div class="section-title" v-if="negativeAssets.length > 0">负债账户</div>
      <van-cell-group inset v-if="negativeAssets.length > 0">
        <van-swipe-cell 
          v-for="item in negativeAssets" 
          :key="item.id"
        >
          <van-cell 
            :title="item.name" 
            :value="`¥${Math.abs(item.money).toFixed(2)}`"
            :label="item.remark"
            :icon="getAssetIcon(item.type)"
            value-class="negative-value"
            @click="editAsset(item)"
            is-link
          />
          <template #right>
            <van-button 
              square 
              text="删除" 
              type="danger" 
              class="swipe-delete-button"
              @click="showDeleteConfirm(item)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>
    </div>

    <!-- 空状态区域（无资产时展示） -->
    <van-empty
      v-if="assetList.length === 0"
      image="https://img.yzcdn.cn/vant/custom-empty-image.png"
      description="定期更新资产账户，轻松掌握资产情况"
      class="empty-section"
    />

    <!-- 添加资产按钮 -->
    <div class="add-asset-btn-wrapper">
      <van-button type="primary" class="add-asset-btn" @click="toAdd"
        >+ 添加资产</van-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { getPropertyList, deleteProperty } from "@/api/index";
import { showSuccessToast, showConfirmDialog } from "vant";
import { useRouter } from "vue-router";

// 初始化路由
const router = useRouter();

// 资产数据
const assetList = ref([]);
const netAssets = ref(0); // 净资产
const assets = ref(0); // 资产总额
const liabilities = ref(0); // 负债总额

// 计算属性：正资产（资产账户）- 根据 type 判断，type !== 7 的为资产
const positiveAssets = computed(() => {
  return assetList.value.filter((item) => item.type !== 7);
});

// 计算属性：负资产（负债账户）- type === 7 的为负债
const negativeAssets = computed(() => {
  return assetList.value.filter((item) => item.type === 7);
});

// 资产类型映射（添加负债类型）
const assetTypeMap = {
  1: "现金",
  2: "储蓄卡",
  3: "信用卡",
  4: "支付宝",
  5: "微信",
  6: "其他",
  7: "负债",
};

// 获取资产类型对应的图标
const getAssetIcon = (type) => {
  const iconMap = {
    1: "cash-o", // 现金
    2: "card", // 储蓄卡
    3: "credit-pay", // 信用卡
    4: "alipay", // 支付宝
    5: "wechat-pay", // 微信
    6: "balance-o", // 其他
    7: "bill-o", // 负债
  };
  return iconMap[type] || "balance-o";
};

/* 生命周期：页面加载时获取数据 */
onMounted(() => {
  fetchAssetData(); // 调用"获取资产数据"方法
});

/* 获取资产数据 */
const fetchAssetData = async () => {
  try {
    const res = await getPropertyList();
    console.log(res);

    assetList.value = res || [];
    console.log(assetList.value);
    calculateTotalAssets();
  } catch (error) {
    console.error("获取资产数据出错:", error);
    showToast("获取资产数据出错");
  }
};

/* 计算总资产、负债和净资产 */
const calculateTotalAssets = () => {
  let totalAssets = 0;
  let totalLiabilities = 0;

  assetList.value.forEach((item) => {
    // 根据 type 判断是资产还是负债
    if (item.type === 7) {
      // 负债类型：取绝对值累加到负债
      totalLiabilities += Math.abs(Number(item.money));
    } else {
      // 其他类型：累加到资产
      totalAssets += Number(item.money);
    }
  });

  assets.value = totalAssets;
  liabilities.value = totalLiabilities;
  netAssets.value = totalAssets - totalLiabilities;
};

/* 顶部导航栏右侧图标点击事件 */
const handleNavRightClick = () => {
  console.log("导航栏右侧图标被点击");
  // 可扩展逻辑：如打开菜单、查看详情等
};

/* 跳转到添加资产页面 */
const toAdd = () => {
  router.push('/asset-type-select');
};

/* 编辑资产 */
const editAsset = (item) => {
  router.push({
    path: '/asset-edit',
    query: { 
      id: item.id,
      type: item.type,
      name: item.name,
      money: item.money,
      remark: item.remark || ''
    }
  });
};

/* 显示删除确认对话框 */
const showDeleteConfirm = (item) => {
  showConfirmDialog({
    title: '删除确认',
    message: `确定要删除"${item.name}"账户吗？`,
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24',
  })
    .then(() => {
      deleteAsset(item.id);
    })
    .catch(() => {
      // 取消删除操作
    });
};

/* 删除资产 */
const deleteAsset = async (id) => {
  try {
    const res = await deleteProperty(id);
    console.log(res);
    if (res == null) {
      showSuccessToast('删除成功');
      // 重新获取资产列表
      fetchAssetData();
    } else {
      showToast(res || '删除失败');
    }
  } catch (error) {
    console.error('删除资产出错:', error);
    showToast('删除资产出错');
  }
};
</script>

<style scoped>
.assets-page-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 60px; /* 为底部导航栏留出空间 */
}

/* 总资产卡片样式：按照图片效果调整布局 */
.total-assets-card {
  background: linear-gradient(135deg, #ffd642 0%, #ffb142 100%);
  color: #333;
  margin: 16px;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  position: relative;
}

.total-assets-card::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 120px;
  height: 120px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0) 70%);
  border-radius: 50%;
  transform: translate(30%, -30%);
  pointer-events: none;
}

.card-title {
  font-size: 14px;
  color: rgba(51, 51, 51, 0.8);
  margin-bottom: 12px;
}

.card-amount {
  font-size: 36px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.card-details {
  display: flex;
  justify-content: space-between;
  position: relative;
  z-index: 1;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-label {
  font-size: 12px;
  color: rgba(51, 51, 51, 0.7);
}

.detail-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.detail-value.negative {
  color: #ff6b6b;
}

/* 资产列表区域样式 */
.asset-list-section {
  margin: 0 16px;
}

/* 区域标题样式 */
.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 16px 8px 8px;
}

/* 负值金额样式 */
:deep(.negative-value) {
  color: #ee0a24 !important;
}

/* 空状态区域样式：居中展示 */
.empty-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 16px;
}

/* 添加资产按钮容器：居中显示 */
.add-asset-btn-wrapper {
  display: flex;
  justify-content: center;
  padding: 24px 16px;
}

/* 添加资产按钮样式：浅灰色，固定宽度 */
.add-asset-btn {
  width: 300px;
  border-radius: 10px;
  height: 44px;
  font-size: 15px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  background: #f5f5f5;
  color: #666;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.add-asset-btn:active {
  transform: scale(0.98);
  background: #e8e8e8;
}

/* 单元格样式 */
:deep(.van-cell) {
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 4px;
  transition: all 0.2s ease;
  background-color: #ffffff;
}

:deep(.van-cell:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.van-cell__title) {
  flex: 3;
  font-weight: 500;
}

:deep(.van-cell__value) {
  flex: 2;
  color: #1989fa;
  font-weight: 600;
  text-align: right;
  font-size: 16px;
}

/* 滑动删除按钮样式 */
.swipe-delete-button {
  height: 100%;
}

/* 响应式布局 */
@media (min-width: 768px) {
  .assets-page-container {
    max-width: 768px;
    margin: 0 auto;
  }
}
</style>
